package com.etrans.util;

import org.apache.commons.lang3.StringUtils;

public class FilterLatLngUtil {
	
	private static int DISTANCEUNIT = 1000;
	
	/**
	 * <p>根据经纬度串运算多点经纬度的总里程</p>
	 * 
	 * @param latlonStr   经纬度串
	 * @param split1            分割每隔经纬度的分隔符
	 * @param split2            分割经度跟纬度的分隔符
	 * @param maxDistance 两点间的最大距离
	 * 
	 * @return distanceAll Integer 返回最后运算的距离[开始经纬度至结束经纬度间的距离]
	 */
	public static String filterLatLng(String latlonStr, String split1,
			String split2, int maxDistance,int precision) {
		if (StringUtils.isEmpty(latlonStr)){
			return null;
		}
		StringBuffer nLatLngSb = new StringBuffer();
		String nLatLng = "";
		//总里程，开始经度，开始纬度
		Integer distanceAll = 0, starLat = 0, starlon = 0,invalidlatlon = 0; 
		String[] latlonAry = latlonStr.split(split1);
		// 球两点间的距离
		for (int i = 0; i < latlonAry.length; i++) {
			String[] latlon = latlonAry[i].split(split2);
			if (i == 0) {
				starLat = Integer.parseInt(latlon[1]);
				starlon = Integer.parseInt(latlon[0]);
				continue;
			}
			Integer currentLat = Integer.parseInt(latlon[1]);
			Integer currentLon = Integer.parseInt(latlon[0]);
			Integer distance = DistanceUtil.GetDistance(starLat, starlon, currentLat, currentLon);
			// 里程转为km double
			double distance_d_km = Double.parseDouble(String.valueOf(distance))/precision;
			// 将最大的点距转为 double
			double maxDistance_km = Double.parseDouble(String.valueOf(maxDistance*(invalidlatlon+1)))/DISTANCEUNIT;
			if(distance_d_km>maxDistance_km){//非法距离直接舍弃该点，跳至下一个点
				invalidlatlon++;
				continue;
			}
			nLatLngSb.append(latlon[0]);
			nLatLngSb.append(",");
			nLatLngSb.append(latlon[1]);
			nLatLngSb.append(";");
			//无效经纬度统计重置
			invalidlatlon=0;
			// 里程求和
			distanceAll+=distance;
			starLat = currentLat;
			starlon = currentLon;
		}
		nLatLng = nLatLngSb.toString();
		if(nLatLng!=null && nLatLng.length()>0){
			nLatLng = nLatLng.substring(0,nLatLng.length()-1);
		}
		return nLatLng;
	}
}
